import 'package:enterprise_v6_app/app/components/custom_modele/custom_search_enter.dart';
import 'package:enterprise_v6_app/app/components/custom_refresh.dart';
import 'package:enterprise_v6_app/app/components/dialog/exit_tips.dart';
import 'package:enterprise_v6_app/app/components/special_operation/custom_select_function.dart';
import 'package:enterprise_v6_app/app/components/special_operation/custom_title_chart_page.dart';
import 'package:enterprise_v6_app/app/components/toast_widget.dart';
import 'package:enterprise_v6_app/app/core/core.dart';
import 'package:enterprise_v6_app/app/core/ext/widget_extension.dart';
import 'package:enterprise_v6_app/app/core/utils/user_manager.dart';
import 'package:enterprise_v6_app/app/data/entities/common/department_user_entity.dart';
import 'package:enterprise_v6_app/app/data/entities/inspec/inspec_query_plan_entity.dart';
import 'package:enterprise_v6_app/app/data/entities/inspec/task_department_list_entity.dart';
import 'package:enterprise_v6_app/app/modules/application/intelligent_inspection_page/manage_inspection_page/manage_inspection_controller.dart';
import 'package:flutter/cupertino.dart';


/// 管理巡检
class ManageInspectionPage extends StatelessWidget {
  ManageInspectionPage({super.key});

  final controller = Get.put(ManageInspectionController());

  /// 单元选择
  Widget _cellSelect() {
    return Row(
      children: [
        Container(
          width: 36.w,
          height: 36.w,
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(8),
            color: Colors.white,
          ),
          child: const Icon(Icons.chevron_left,size: 25,),
        ).clickOnce(() {
          controller.selectDepartment(false);
        }),
        AppGaps.hGap10,
        Expanded(
          child: Container(
            height: 36.w,
            padding: EdgeInsets.only(
              left: 14.w,
              right: 14.w,
            ),
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(8),
              color: Colors.white,
            ),
            child: Row(
              children: [
                Expanded(
                  child: Text(
                    controller.selectDepar != -1 ?  '${controller.queryDeparList[controller.selectDepar].riskUnitName}' : '请选择',
                    style: AppTextStyles.black_16_bold,
                    overflow: TextOverflow.ellipsis,
                  ),
                ),
                Text(
                  '${controller.selectDepar+ 1}/${controller.queryDeparList.length}',
                  style: AppTextStyles.gray_12,
                )
              ],
            ),
          ),
        ),
        AppGaps.hGap10,
        Container(
          width: 36.w,
          height: 36.w,
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(8),
            color: Colors.white,
          ),
          child: const Icon(Icons.chevron_right,size: 25,),
        ).clickOnce(() {
          controller.selectDepartment(true);
        }),
      ],
    );
  }

  //筛选按钮
  // Widget _getFilter() {
  //   return Container(
  //     width: 38.w,
  //     height: 38.w,
  //     alignment: Alignment.center,
  //     decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(8.w)),
  //     child: SvgPicture.asset(
  //       AppImages.icon_search_screen,
  //       width: 16.w,
  //     ),
  //   ).click(() {
  //     controller.rightScaffoldKey.currentState?.openEndDrawer();
  //   });
  // }

  /// 展开 & 收起
  /// [item]
  Widget _getExpand(TaskDepartmentListEntity item) {
    return Row(
      children: [
        Text(item.isExpanded ? '展开' : '收起',style: TextStyle(
          fontSize: 14.sp,
          color: const Color(0xFF5C6DFF),
        ),),
        AppGaps.hGap4,
        Transform.rotate(
          angle: item.isExpanded ? 0 : 180 * 3.14159 / 180,
          child: Icon(
            Icons.expand_circle_down_outlined,
            size: 15.w,
            color: const Color(0xFF5C6DFF),
          ),
        ),
      ],
    ).click(() {
      controller.clickExpand(item);
    });
  }

  Color _color(int? i) {
    switch(i) {
      case 1:
        return Colors.grey[100]!;
      case 2:
        return AppColors.font_color_blue;
      default:
        return Colors.grey[100]!;
    }
  }

  /// 列表任务详情
  /// 可以被24整除的
  /// 1（24）、2（12）、3（8）、4（6）、6（4）、8（3）、12（2）
  Widget _getTaskDetail(TaskDepartmentListEntity item,int i,int currentIndex) {
    final List<TaskDepartmentListTaskTimeNodeTables> list = item.taskTimeNodeTables ?? [];
    if(item.isExpanded) {
      return Row(
        children: list.map((e) {
          return Expanded(
            child: Column(
              children: [
                Container(
                  height: 14.w,
                  margin: EdgeInsets.only(left: 1.w,right: 1.w),
                  alignment: Alignment.center,
                  decoration: BoxDecoration(
                      color: AppColors.font_color_blue,
                      borderRadius: BorderRadius.circular(1)
                  ),
                ),
                AppGaps.vGap4,
                Text('${e.startDate}',maxLines: 1,style: TextStyle(
                  fontSize: 9.sp,
                  color: AppColors.font_color_blue,
                ),)
              ],
            ),
          );
        }).toList(),
      );
    } else {
      return GridView.builder(
          shrinkWrap: true,
          physics: const NeverScrollableScrollPhysics(),
          gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: 4,
            crossAxisSpacing: 7,
            mainAxisSpacing: 20,
          ),
          itemCount: list.length,
          itemBuilder: (BuildContext ctx, index) {
            return Container(
              alignment: Alignment.center,
              decoration: BoxDecoration(
                color: list[index].currentRecipient ? const Color(0xFFFC9900) : _color(list[index]
                    .hasItBeenClaimed),
                borderRadius: BorderRadius.circular(6),
              ),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Text('${list[index].startDate}:00',style: TextStyle(
                    color: list[index].hasItBeenClaimed == 2 ? Colors.white : AppColors.font_color_gray,
                    fontSize: 13.sp,
                    fontWeight: FontWeight.w500,
                  )),
                  AppGaps.vGap4,
            // list[index].hasItBeenClaimed == 1 && (UserManager.getUser()?.systemUser?.nickname == list[index].recipientName) ? Text('${list[index].recipientName}',style: TextStyle(
            list[index].hasItBeenClaimed == 1 ? Text('${list[index].recipientName}',style: TextStyle(
                    fontSize: 12.sp,
                    color: AppColors.font_color_gray,
                  ),) : Container(
                    padding: const EdgeInsets.only(left: 8,right: 8,top: 1,bottom: 1),
                    decoration: BoxDecoration(
                        color: const Color(0x26FFFFFF),
                        borderRadius: BorderRadius.circular(12)
                    ),
                    child: Text( list[index].currentRecipient ? '撤销': '分配',style: TextStyle(
                      color: Colors.white,
                      fontSize: 12.sp,
                    )),
                  ).clickOnce(() {
                    controller.taskClaim(list[index],currentIndex);
                  }),
                ],
              ),
            );
          });
    }
  }

  /// 选中任务后显示的页面
  Widget _selectView() {
    return Visibility(
      visible: controller.isSubmitted,
      child: Container(
        padding: EdgeInsets.only(left: 12.w,top: 14.w,right: 20.w,bottom: 40.w),
        margin: EdgeInsets.only(bottom: 20.w),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(12),
        ),
        child: Stack(
          children: [
            Container(
              width: 1.w,
              height: AppDimens.sh,
              margin: EdgeInsets.only(left: 4.w,top: 10.w,),
              color: AppColors.font_color_blue,
            ),
            ListView.builder(
              itemCount: controller.timeList.length,
              itemBuilder: (cxt, index) {
                return Column(
                  mainAxisAlignment: MainAxisAlignment.start,
                  children: [
                    SizedBox(
                      height: 30.w,
                      // color: Colors.greenAccent.withOpacity(0.3),
                      child: Row(
                        // crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Container(
                            width: 10.w,
                            height: 10.w,
                            padding: const EdgeInsets.all(2),
                            decoration: BoxDecoration(
                                color: AppColors.font_color_blue, borderRadius: BorderRadius.circular(90)),
                            child: Container(
                              decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(4)),
                            ),
                          ),
                          AppGaps.hGap6,
                          Text(
                            '${controller.timeList[index].time}:00',
                            style: TextStyle(
                              fontSize: 15.sp,
                              fontWeight: FontWeight.w500,
                            ),
                          ),
                        ],
                      ),
                    ),
                    ListView.builder(
                      shrinkWrap: true,
                      physics: const NeverScrollableScrollPhysics(),
                      padding: EdgeInsets.only(left: 16.w,bottom: 10.w),
                      itemCount: controller.timeList[index].tasks.length,
                      itemBuilder: (cxt, i) {
                        return SizedBox(
                          height: 25.w,
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Text('${i + 1}.${controller.timeList[index].tasks[i].taskName}',
                                  style: TextStyle(color: AppColors.font_color_gray, fontSize: 13.sp)),
                              Container(
                                height: 25.w,
                                padding: const EdgeInsets.only(left: 5,right: 5),
                                child: Text(
                                  '移除',
                                  style: TextStyle(
                                    color: AppColors.font_color_blue,
                                    fontSize: 13.sp,
                                  ),
                                ),
                              ).click(() {
                                controller.removeTask(index,i);
                              })
                            ],
                          ),
                        );
                      },
                    ),
                  ],
                );
              },
            ),
          ],
        ),

      ),
    );
  }

  /// 弹窗是选择方案
  _selectPlan() {
    CustomSelectFunction.selectMultipleBottomSheet<InspecQueryPlanEntity>(
      title: '请选择',
      isMultiple: false,
      dataList: controller.alreadyPlan,
      checkedList: controller.selectAlreadyPlan != null ? [
        controller.alreadyPlan[controller.selectAlreadyPlan!],
      ] : [],
      onCallBack: (value) {
        if(value.isNotEmpty) {
          controller.selectAlreadyPlan = controller.alreadyPlan.indexOf(value[0]);
        }
        controller.update(['dialog']);
      },
    );
  }

  /// 人员选择
  _person() {
    CustomSelectFunction.selectMultipleBottomSheet<DepartmentUserEntity>(
      title: '请选择',
      isMultiple: false,
      dataList: controller.personList,
      checkedList: [],
      onCallBack: (value) {
        if(value.isNotEmpty) {
          controller.selectPerson = controller.personList.indexOf(value[0]);
        }
        controller.update(['dialog']);
      },
    );
  }

  /// 任务提交
  _taskSubmit() {
    Get.dialog(
        GetBuilder(
          id: 'dialog',
          init: controller,
          builder: (_) {
            return Container(
              alignment: Alignment.center,
              child: Container(
                width: AppDimens.sw - 24.w,
                height: 350.w,
                decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.all(Radius.circular(20.w)),
                  gradient: const LinearGradient(
                    //渐变位置
                      begin: Alignment.topCenter,
                      end: Alignment.bottomCenter,
                      //渐变颜色[始点颜色, 结束颜色]
                      colors: [
                        Color(0xffE7EAFF),
                        Color(0xffffffff),
                        Color(0xffffffff),
                        Color(0xffffffff),
                      ]),
                ),
                child: Stack(
                  alignment: Alignment.center,
                  children: [
                    Container(
                        padding: EdgeInsets.symmetric(horizontal: 16.w),
                        child: Column(
                          children: [
                            AppGaps.vGap20,
                            Text(
                              '任务提交',
                              style: TextStyle(
                                color: Colors.black,
                                fontSize: 18.sp,
                                fontWeight: FontWeight.bold,
                              ),
                            ),
                            AppGaps.vGap24,
                            // 人员选择
                            Row(
                              children: [
                                Text('人员选择',style: TextStyle(
                                  fontSize: 14.sp,
                                  color: Colors.black,
                                ),),
                                AppGaps.hGap12,
                                Expanded(
                                  child: Container(
                                    height: 32.w,
                                    padding: EdgeInsets.symmetric(horizontal: 10.w),
                                    alignment: Alignment.center,
                                    decoration: BoxDecoration(
                                      borderRadius: BorderRadius.circular(8),
                                      border: Border.all(
                                        color: AppColors.bg_color_grey,
                                      ),
                                    ),
                                    child: Row(
                                      children: [
                                        Text(
                                            controller.selectPerson != null
                                                ? controller
                                                .personList[controller.selectPerson!]
                                                .getShowName()
                                                : '请选择人员',
                                            style: TextStyle(
                                              fontSize: 14.sp,
                                              color: AppColors.font_color_gray,
                                            )),
                                        const Spacer(),
                                        const Icon(Icons.arrow_drop_down_outlined,color: AppColors.font_color_gray),
                                      ],
                                    ),
                                  ).click(_person),
                                )
                              ],
                            ),
                            // 是否记住
                            Column(
                              children: [
                                // 是否加入已有方案
                                Row(
                                  children: [
                                    Text('是否加入已有方案',style: TextStyle(
                                      fontSize: 14.sp,
                                      color: Colors.black,
                                    ),),
                                    const Spacer(),
                                    Container(
                                        padding: EdgeInsets.symmetric(vertical: 20.w),
                                        child: Row(
                                          mainAxisSize: MainAxisSize.min,
                                          mainAxisAlignment: MainAxisAlignment.start,
                                          children: [
                                            controller.isAddPlan ? SvgPicture.asset(
                                              AppImages.icon_select,
                                              height: 16.w,
                                              width: 16.w,
                                            )
                                                : SvgPicture.asset(
                                              AppImages.icon_un_select,
                                              height: 16.w,
                                              width: 16.w,
                                            ),
                                            AppGaps.hGap4,
                                            Text(
                                              '是',
                                              style: TextStyle(
                                                height: 1.2,
                                                color: const Color(0xff8D95A3),
                                                fontSize: 14.sp,
                                                fontWeight: FontWeight.w400,
                                              ),
                                            )
                                          ],
                                        )).click(() {
                                      controller.clickAddPlan(true);
                                    }),
                                    AppGaps.hGap20,
                                    Container(
                                        padding: EdgeInsets.symmetric(vertical: 20.w),
                                        child: Row(
                                          mainAxisSize: MainAxisSize.min,
                                          mainAxisAlignment: MainAxisAlignment.start,
                                          children: [
                                            !controller.isAddPlan ? SvgPicture.asset(
                                              AppImages.icon_select,
                                              height: 16.w,
                                              width: 16.w,
                                            )
                                                : SvgPicture.asset(
                                              AppImages.icon_un_select,
                                              height: 16.w,
                                              width: 16.w,
                                            ),
                                            AppGaps.hGap4,
                                            Text(
                                              '否',
                                              style: TextStyle(
                                                height: 1.2,
                                                color: const Color(0xff8D95A3),
                                                fontSize: 14.sp,
                                                fontWeight: FontWeight.w400,
                                              ),
                                            )
                                          ],
                                        )).click(() {
                                      controller.clickAddPlan(false);
                                    })
                                  ],
                                ),
                                // 方案名称
                                Visibility(
                                  visible: !controller.isAddPlan,
                                  child: Container(
                                    margin: const EdgeInsets.only(top: 10),
                                    child: Row(
                                      children: [
                                        Text('方案名称',style: TextStyle(
                                          fontSize: 14.sp,
                                          color: Colors.black,
                                        ),),
                                        AppGaps.hGap12,
                                        Expanded(
                                          child: CupertinoTextField(
                                            placeholder: '请输入方案名称',
                                            placeholderStyle: TextStyle(
                                                fontSize: 14.sp,
                                                color: AppColors.font_color_gray
                                            ),
                                            onChanged: (v) {
                                              controller.inputSchemeName = v;
                                            },
                                          ),
                                        )
                                      ],
                                    ),
                                  ),
                                ),
                                // 选择已有方案
                                Visibility(
                                  visible: controller.isAddPlan,
                                  child: Row(
                                    children: [
                                      Text('方案名称',style: TextStyle(
                                        fontSize: 14.sp,
                                        color: Colors.black,
                                      ),),
                                      AppGaps.hGap12,
                                      Expanded(
                                        child: Container(
                                          height: 32.w,
                                          padding: EdgeInsets.symmetric(horizontal: 10.w),
                                          alignment: Alignment.center,
                                          decoration: BoxDecoration(
                                            borderRadius: BorderRadius.circular(8),
                                            border: Border.all(
                                              color: AppColors.bg_color_grey,
                                            ),
                                          ),
                                          child: Row(
                                            children: [
                                              Text(
                                                  controller.selectAlreadyPlan != null
                                                      ? controller
                                                      .alreadyPlan[controller.selectAlreadyPlan!]
                                                      .getShowName()
                                                      : '请选择方案名称',
                                                  style: TextStyle(
                                                    fontSize: 14.sp,
                                                    color: AppColors.font_color_gray,
                                                  )),
                                              const Spacer(),
                                              const Icon(Icons.arrow_drop_down_outlined,color: AppColors.font_color_gray),
                                            ],
                                          ),
                                        ).click(_selectPlan),
                                      )
                                    ],
                                  ),
                                ),
                              ],
                            ),
                            // 提交
                            const Spacer(),
                            SizedBox(
                              width: 270.w,
                              height: 40.w,
                              child: ElevatedButton(
                                style: ButtonStyle(
                                  backgroundColor: MaterialStateProperty.all(
                                      const Color(0xff5C6DFF)),
                                ),
                                onPressed: controller.submitButton,
                                child: Text(
                                  '提交',
                                  style:
                                  TextStyle(fontSize: 16.sp, color: Colors.white),
                                ),
                              ),
                            ),
                            AppGaps.vGap20,
                          ],
                        )),
                    Positioned(
                        top: 8,
                        right: 8,
                        child: IconButton(
                          icon: Container(
                            width: 30.w,
                            height: 30.w,
                            decoration: BoxDecoration(
                              color: Colors.white,
                              borderRadius: BorderRadius.all(Radius.circular(15.w)),
                            ),
                            child: Icon(
                              Icons.close,
                              color: Colors.grey,
                              size: 21.w,
                            ),
                          ),
                          onPressed: Get.back,
                        )),
                  ],
                ),
              ),
            );
          },
        )
    );
  }


  @override
  Widget build(BuildContext context) {
    return GetBuilder(
      init: controller,
      // initState: (_) {
      //   controller.queryTaskList(1);
      // },
      builder: (_) {
        return PopScope(
          canPop: controller.selectTaskIdList.isEmpty,
          onPopInvoked: (didPop) {
            if (didPop) {
              return;
            }
            Get.dialog<bool>(ExitTips(
              content: '将清空之前操作，确认继续吗？',
              func: (v) {
                if (v) {
                  Get.back();
                } else {
                  return false;
                }
              },
            ));
          },
          child: Scaffold(
            key: controller.rightScaffoldKey,
            body: Container(
              padding: EdgeInsets.only(
                top: 12.w,
                right: 14.w,
                left: 14.w,
              ),
              color: AppColors.bg_color_grey,
              child:  Stack(
                children: [
                  Column(
                    children: [
                      _cellSelect(),
                      AppGaps.vGap10,
                      Row(
                        children: [
                          Expanded(
                            child: CustomSearchEnter(
                              height: 38.w,
                              hintText: '输入任务名称',
                              // text: controller.taskName,
                              onCallBack: controller.inputTaskName,
                            ),
                          ),
                          // AppGaps.hGap10,
                          // _getFilter(),
                        ],
                      ),
                      AppGaps.vGap10,
                      Expanded(
                          child: CustomEasyRefreshList<TaskDepartmentListEntity>(
                            key: controller.globalKey,
                            dataLoad: (index,size,{search}) async {
                              return controller.queryTaskListByDepartment(num: index,size: size);
                            },
                            itemBuilder: (item,index) {
                              return CustomTitleChartPage(
                                title: '${item.riskMeasureName}',
                                titleRightWidget: _getExpand(item),
                                child: Column(
                                  children: [
                                    Row(
                                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                      children: [
                                        Text('任务名称 :',style: AppTextStyles.grey_14,),
                                        Expanded(child: Text(
                                          '${item.troubleshootContent}',
                                          style: AppTextStyles.black_14,)),
                                      ],
                                    ),
                                    AppGaps.vGap8,
                                    _getTaskDetail(
                                        item,
                                        item.taskTimeNodeTables != null ?
                                        item.taskTimeNodeTables!.length : 0,
                                        index
                                    ),
                                  ],
                                ),
                              );
                            },
                          )
                      ),
                    ],
                  ),
                  _selectView(),
                ],
              ),
            ),
            bottomSheet: Container(
              height: 45.w,
              color: Colors.white,
              child: controller.isSubmitted ? Row(
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                children: [
                  Container(
                    width: 90.w,
                    height: 40.w,
                    alignment: Alignment.center,
                    decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(24),
                        border: Border.all(
                          color: AppColors.font_color_blue,
                          width: 1,
                        )
                    ),
                    child: Text('取消',style: TextStyle(
                      fontSize: 16.sp,
                      color: AppColors.font_color_blue,
                    ),),
                  ).clickOnce(controller.cancelTask),
                  Container(
                    width: 120.w,
                    height: 40.w,
                    alignment: Alignment.center,
                    decoration: BoxDecoration(
                      color: AppColors.font_color_blue,
                      borderRadius: BorderRadius.circular(24),
                    ),
                    child: Text('提交',style: TextStyle(
                      fontSize: 16.sp,
                      color: Colors.white,
                    ),),
                  ).clickOnce(() {
                    if(controller.selectTaskIdList.isEmpty) {
                      AppToast.showWarning('请选择至少一个任务');
                      return;
                    }
                    _taskSubmit();
                  })
                ],
              ) : Row(
                children: [
                  AppGaps.hGap12,
                  Text('已选择 ${controller.selectTaskIdList.length} 个',style: AppTextStyles.blue_16,),
                  const Spacer(),
                  Container(
                    width: 130.0.w,
                    height: 45.0.w,
                    color: AppColors.font_color_blue,
                    alignment: Alignment.center,
                    child: Text('提交',
                        style: TextStyle(
                          fontSize: 15.sp,
                          color: Colors.white,
                          fontWeight: FontWeight.w500,
                        )),
                  ).clickOnce(controller.selectTask),
                ],
              ),
            ),
          ),
        );
      },
    );
  }
}
